﻿using AutoMapper;
using BlogDemo.Core.Entities;
using BlogDemo.Core.Interface;
using BlogDemo.Infrastructure.Dtos;
using BlogDemo.Infrastructure.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace BlogDemo.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PostsController : ControllerBase
    {
        private readonly IPostRepository _postRepository;
        private readonly IUnitOfWork _uw;
        private readonly ILogger<PostsController> _logger;
        private readonly IConfiguration _configuration;
        private readonly IMapper _mapper;
        public PostsController(IPostRepository postRepository,
            IUnitOfWork uw,
            ILogger<PostsController> logger,
            IConfiguration configuration,
            IMapper mapper)
        {
            _postRepository = postRepository;
            _uw = uw;
            //_logger = loggerFactory.CreateLogger(typeof(PostsController));
            _logger = logger;
            _configuration = configuration;
            _mapper = mapper;
        }
        public async Task<PostDto> GetAsync(int id)
        {
            var dto = await _postRepository.GetByIdAsync(id);
            if (dto != null)
            {
                return _mapper.Map<Post, PostDto>(dto);
            }
            return null;
        }
        public async Task<PagedList<PostDto>> GetAllAsync([FromQuery]PostParameters postParameters)
        {
            var myConn = _configuration.GetConnectionString("DefaultConnection");
            _logger.LogInformation($"翻阅了所有文章！{myConn}");
            return _mapper.Map<PagedList<Post>, PagedList<PostDto>>(await _postRepository.GetAllAsync(postParameters.Title,postParameters.PageIndex,postParameters.PageSize,postParameters.OrderBy));
        }
        [HttpPost]
        public async Task AddAsync(PostInputDto input)
        {
            if (ModelState.IsValid)
            {
                var post = new Post() { Author = input.Author, Body = input.Body, Title = input.Title };
                await _postRepository.AddAsync(post);
            }
            //await _uw.SaveChangesAsync();
        }
        public class PostParameters
            : QueryParameters
        {
            public string Title { get; set; }
        }
    }
}